package com.white.loggerserver

import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import androidx.recyclerview.widget.LinearLayoutManager
import com.white.loggerserver.room.MyRoomDb
import com.white.loggerserver.room.Record
import kotlinx.android.synthetic.main.activity_log_record_list.*
import kotlin.concurrent.thread
import kotlin.properties.Delegates

class LogRecordListActivity : AppCompatActivity() {

    private var files = mutableListOf<Record>()
    private var adapter : LogRecordAdapter by Delegates.notNull()

    companion object {
        fun active(act: Activity) {
            val it = Intent(act, LogRecordListActivity::class.java)
            act.startActivity(it)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_log_record_list)
        supportActionBar?.let {
            it.title = "日志文件"
            it.setDisplayHomeAsUpEnabled(true)
        }

        adapter = LogRecordAdapter()
        recycle.layoutManager = LinearLayoutManager(this)
        recycle.adapter = adapter
        adapter.setNewInstance(files)
        adapter.setOnItemClickListener { adapter, view, position ->
            LogDetailActivity.active(this@LogRecordListActivity, files[position])
        }
        req()
    }

    private fun req(){
        thread {
            val records = MyRoomDb.instance.recordDao().getAllRecord()
            records?.let {
                runOnUiThread{
                    adapter.addData(records)
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == 2 && resultCode == Activity.RESULT_OK){
            val it = data?.getParcelableExtra<Record>("item")
            it?.let {
                MyRoomDb.instance.recordDao().delRecord(it)
                adapter.remove(it)
            }
        }
    }


    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            android.R.id.home->{
                finish()
            }
        }
        return true
    }
}